package com.cxs.musicplaywidget.commonevent;

import com.cxs.musicplaywidget.data.EventParam;
import com.cxs.musicplaywidget.player.data.MusicInfo;
import ohos.aafwk.ability.Ability;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationSlot;
import ohos.rpc.RemoteException;

/**
 * @ClassName NotificationManager
 * @Author cxs
 * @Version 1.0
 * @Description TODO
 * @Date 2022/03/15
 */
public class NotificationManager {
    private static NotificationManager instance;
    private final Context context;
    private static final int NOTIFICATION_ID = 1;
    private static NotificationSlot slot = null;

    private NotificationManager(Context context) {
        this.context = context;
    }

    public static NotificationManager getInstance(Context context) {
        if (instance == null) {
            synchronized (NotificationManager.class) {
                if (instance == null) {
                    instance = new NotificationManager(context);
                }
            }
        }
        return instance;
    }

    public void sendNotification(EventParam eventParam) {
        NotificationSlot slot = getSlot();

        NotificationRequest request = new NotificationRequest(NOTIFICATION_ID);
        request.setSlotId(slot.getId());

        String title = "音乐播放器";
        NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
        MusicInfo musicInfo = eventParam.getMusicInfo();
        if (musicInfo != null) {
            content.setText(musicInfo.getTitle());
        }
        content.setTitle(title);
        NotificationRequest.NotificationContent notificationContent = new
                NotificationRequest.NotificationContent(content);
        request.setContent(notificationContent);

        // 启动长驻任务，长驻任务实现的关键方法
        ((Ability)context).keepBackgroundRunning(NOTIFICATION_ID, request);
    }

    private NotificationSlot getSlot() {
        if (slot != null) {
            return slot;
        }
        String slotId = "110";
        String slotName = "音乐播放卡片服务";
        NotificationSlot slot = new NotificationSlot(slotId, slotName, NotificationSlot.LEVEL_MIN);
        slot.setDescription("NotificationSlot Description");
        try {
            NotificationHelper.addNotificationSlot(slot);   // 添加渠道
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return slot;
    }

    public void cancelNotification() {
        ((Ability)context).cancelBackgroundRunning();
    }
}
